package com.yutel.phone.juny.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class IncomingSMSIntentService extends IntentService {
	private static String TAG = "IncomingSMSIntentService";

	public IncomingSMSIntentService() {
		super("IncomingSMSIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Context context = getBaseContext();
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		// Let the phone ring for a set delay
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			SmsMessage[] messages = new SmsMessage[pdus.length];
			for (int i = 0; i < pdus.length; i++)
				messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
			for (SmsMessage message : messages) {
				String msg = message.getMessageBody();
				String addr = message.getOriginatingAddress();
				Log.i(TAG, "from=" + addr + ",msg=" + msg);
				exec(addr, msg, prefs);
			}
		}
	}

	private void exec(String addr, String msg, SharedPreferences prefs) {
		String from = prefs.getString("smsaddress", null);
		if (from != null && from.equals(addr)) {
			if (msg != null) {
				String[] lines = msg.split(",");
				if (lines.length == 1) {
					if ("juny1103".equals(lines[0])) {
						Editor editor = prefs.edit();
						editor.putBoolean("callenabled", true);
						editor.putString("callaction", "answer");
						editor.commit();
					} else if ("binh1110".equals(lines[0])) {
						Editor editor = prefs.edit();
						editor.putBoolean("callenabled", false);
						editor.putString("callaction", "refuse");
						editor.commit();
					}
				} else if (lines.length > 1) {
					if ("e:1".equalsIgnoreCase(lines[0])) {
						Editor editor = prefs.edit();
						editor.putBoolean("callenabled", true);
						editor.commit();
					} else if ("e:0".equalsIgnoreCase(lines[0])) {
						Editor editor = prefs.edit();
						editor.putBoolean("callenabled", false);
						editor.commit();
					}
					if ("r:1".equalsIgnoreCase(lines[1])) {
						Editor editor = prefs.edit();
						editor.putString("callaction", "answer");
						editor.commit();
					} else if ("r:0".equalsIgnoreCase(lines[1])) {
						Editor editor = prefs.edit();
						editor.putString("callaction", "refuse");
						editor.commit();
					}
				}
			}
		}
	}
}
